package cn.zsc.netdisk.service;

import cn.zsc.netdisk.common.Paths;
import cn.zsc.netdisk.common.UserInfo;
import cn.zsc.netdisk.exception.SharePasswordException;
import cn.zsc.netdisk.exception.ShareUrlException;
import cn.zsc.netdisk.mapper.ShareMapper;
import cn.zsc.netdisk.pojo.Share;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author ccying
 * @date 2021/3/9
 */
@Service
@Slf4j
public class ShareService {
    private final ShareMapper mapper;

    public ShareService(ShareMapper mapper) {
        this.mapper = mapper;
    }

    /**
     * 生成文件分享链接
     * @param name 后台文件路径名
     * @return 分享链接信息
     * */
    public Share to(String name) {
        log.info("生成文件分享链接");
        //用户账号
        String uid = UserInfo.getPrincipal();
        //时间戳
        String time = String.valueOf(System.currentTimeMillis());
        //前台文件路径名
        name = name.substring(Paths.TEMP_ROOT_PATH_SHARE.length());
        //链接url
        String url = String.format("%s/%s/%s", uid, time, name);
        //密码
        int password = (int) (Math.random() * 1000000);
        //分享链接信息
        Share share = new Share();
        share.setUid(uid);
        share.setName(name);
        share.setUrl(url);
        share.setPassword(password);
        log.info("文件链接：" + share.toString());
        return share;
    }

    /**
     * 增加一条文件分享链接记录
     * @param share 文件分享链接信息
     * */
    public void add(Share share) throws Exception {
        log.info("增加一条文件分享链接记录");
        this.mapper.add(share);
    }

    /**
     * 删除所有分享链接记录
     * */
    public void deleteAll() throws Exception {
        log.info("删除所有分享链接记录");
        this.mapper.deleteAll();
    }

    /**
     * 验证分享url和密码是否正确
     * @param url 分享链接url
     * @param password 分享链接密码
     * @throws ShareUrlException 分享链接不存在
     * @throws SharePasswordException 分享密码错误
     * @return 分享文件名
     * */
    public String verify(String url, int password) throws ShareUrlException, SharePasswordException{
        log.info("验证分享url和密码是否正确");
        Share share = this.mapper.findShareByUrl(url);
        if (share == null) {
            throw new ShareUrlException("分享链接不存在");
        }
        //前端密码值加123456加密发送
        password = password - 123456;
        if (password != share.getPassword()) {
            throw new SharePasswordException("分享密码错误");
        }
        return share.getName();
    }

    /**
     * 查询所有分享用户
     * */
    public String[] findAllShareUid() {
        return this.mapper.findAllShareUid();
    }

}
